package com.shj.em.common.to;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.shj.em.util.StringUtils;
import lombok.Data;

/**
 * Author: Shen Huang Jian
 *
 * @param <T>
 */
@Data
public class Tree<T> {
	/**
	 * 节点ID
	 */
	private String id;
	/**
	 * 显示节点文本
	 */
	private String name;

	private String icon;

	private String path;

	/**
	 * 节点的子节点
	 */
	private List<Tree<T>> child = new ArrayList<Tree<T>>();

	/**
	 * 父ID
	 */
	private String parentId;
	/**
	 * 是否有父节点
	 */
	private boolean hasParent = false;
	/**
	 * 是否有子节点
	 */
	private boolean hasChildren = false;


    public static <T> List<Tree<T>> buildTree(List<Tree<T>> nodes, String idParam) {
        if (nodes == null) {
            return null;
        }
        List<Tree<T>> topNodes = new ArrayList<Tree<T>>();

        for (Tree<T> children : nodes) {

            String pid = children.getParentId();
            if (pid == null || idParam.equals(pid)) {
                topNodes.add(children);

                continue;
            }

            for (Tree<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    parent.getChild().add(children);
					children.setParentId(id);
                    continue;
                }
            }

        }
        return topNodes;
    }

    public boolean getHasParent(){
    	return StringUtils.isNotBlank(parentId);
	}

	public boolean getHasChildren(){
    	return child.size() > 0;
	}

	@Override
	public String toString() {
		return JSON.toJSONString(this);
	}

}